/*
 * @Copyright: 2025 Copyright (C) AMCAX, All rights reserved.
 * @Author: Zhang
 * @Date: 2025/7/24 19:39
 * @LastEditTime: 2025/7/24 19:39
 * @LastEditors: Zhang
 * @Description:
 */
import { TopoDialogProps, NMMeshBaseCommand } from '../type';

import { CmdDialogForm, userEvents, ModelEventType } from 'nextcae-base';
import { useEffect, useState, useRef } from 'react';
import './index.scss';
import { surfEvaluate } from '@/domain';
import { schema, uiSchema } from './data';
import { widgetManager } from '@/common/managers';
import { makeId } from '@/common/utils';
import { clearFields, renderFields } from '@/common/utils/renderUtils';
import { isArray } from 'lodash';

const CurveOptimizationDialog = ({ title, onClose }: TopoDialogProps) => {
  const [formData, setFormData] = useState({
    Selection: {
      Source: [],
      target: [],
    },
  });
  const reqRef = useRef(null);

  useEffect(() => {
    widgetManager.hint('进入形变误差分析命令!');
    return () => {
      widgetManager.hint();
    };
  }, []);

  // 提交
  const onSubmit = async () => {
    const params = {
      surface1: formData?.Selection?.Source?.map((item) => makeId(item))[0],
      surface2: formData?.Selection?.target?.map((item) => makeId(item))[0],
    };
    const req = await surfEvaluate.getDeformError(params);
    if (!isArray(req)) return;
    renderFields(req);
    req.forEach((item) => {
      userEvents.emit(ModelEventType.SetColormap, 'jet');
      userEvents.emit(ModelEventType.SetExtra, item.extra);
    });
    reqRef.current = req;
    onClose();
  };
  return (
    <>
      <CmdDialogForm
        title={title}
        titleIcon={'commands/surfaceAnalysis/deform-error'}
        schema={schema}
        extraUiSchema={uiSchema}
        formData={formData}
        fields={{}}
        onChange={(data) => {
          setFormData(data.formData);
        }}
        onSubmit={onSubmit}
        onClose={onClose}
        isFormDataValid={
          formData?.Selection?.Source.length > 0 ||
          formData?.Selection?.target.length > 0
        }
        width='300px'
        formClassName='structure-form'
      />
    </>
  );
};
export const cmdDeformationError: NMMeshBaseCommand = {
  id: 'cmdDeformationError',
  icon: 'commands/surfaceAnalysis/deform-error',
  label: '形变误差分析',
  create: (label: string, onClose: () => void, props) => (
    <CurveOptimizationDialog
      title={label}
      onClose={onClose}
      props={props}
      placement='topLeft'
    />
  ),
};
